﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Loaf.自定义控件.Controls
{
    public class ColorPicker : Control
    {
        /*
         * 使用说明
         * 绑定得到的是 SolidColorBrush 而不是 Color
         * 因为 Color 是 Struct 不可以进行绑定
         */

        public static readonly DependencyProperty AProperty = DependencyProperty.Register(nameof(A), typeof(int), typeof(ColorPicker), new PropertyMetadata(255, OnArgbChange));
        public static readonly DependencyProperty RProperty = DependencyProperty.Register(nameof(R), typeof(int), typeof(ColorPicker), new PropertyMetadata(0, OnArgbChange));
        public static readonly DependencyProperty GProperty = DependencyProperty.Register(nameof(G), typeof(int), typeof(ColorPicker), new PropertyMetadata(0, OnArgbChange));
        public static readonly DependencyProperty BProperty = DependencyProperty.Register(nameof(B), typeof(int), typeof(ColorPicker), new PropertyMetadata(0, OnArgbChange));
        public static DependencyProperty BrushProperty = DependencyProperty.Register(nameof(Brush), typeof(SolidColorBrush), typeof(ColorPicker), new PropertyMetadata(null));

        public int A { get => (int)GetValue(AProperty); set => SetValue(AProperty, value); }
        public int R { get => (int)GetValue(RProperty); set => SetValue(AProperty, value); }
        public int G { get => (int)GetValue(GProperty); set => SetValue(AProperty, value); }
        public int B { get => (int)GetValue(BProperty); set => SetValue(AProperty, value); }

        public SolidColorBrush Brush { get => (SolidColorBrush)GetValue(BrushProperty); set => SetValue(BrushProperty, value); }


        private DockPanel Display { get; set; }

        public void ShowColor()
        {
            if (Display == null)
                Display = this.Template.FindName("display", this) as DockPanel;

            Brush.Color = Color.FromArgb((byte)A, (byte)R, (byte)G, (byte)B);

            Display.Children.Clear();
            Display.Children.Add(new Border()
            {
                Background = Brush
            });
        }

        private static void OnArgbChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (ColorPicker)d;
            control.ShowColor();
        }

    }
}
